package cn.net.yato.picture.util.encryption;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @ClassName DateTools
 * @Description 日期工具类
 * @Author yato
 * @Date 2020/1/11 9:22
 * @Version 1.0
 */
public class DateTools {

    /**
     * 获取日期年份
     * @param date
     * @return
     */
    public static int getYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 得到当前Date类型日期
     *
     * @param formatStr
     * @return
     * @throws ParseException
     */
    public static Date getCurrentDate(String formatStr) throws ParseException {
        SimpleDateFormat simpleDateFormat = SimpleDateFormatInit.getSimpleDateFormat(formatStr);
        return simpleDateFormat.parse(simpleDateFormat.format(new Date()));
    }

    /**
     * 得到当前字符串类型日期
     *
     * @param formatStr
     * @return
     */
    public static String getCurrentDateStr(String formatStr) {
        return SimpleDateFormatInit.getSimpleDateFormat(formatStr).format(new Date());
    }

    /**
     * Date to Str
     *
     * @param date
     * @param formatStr
     * @return
     */
    public static String dateToStr(Date date, String formatStr) {
        return SimpleDateFormatInit.getSimpleDateFormat(formatStr).format(date);
    }

    /**
     * Str to Date
     *
     * @param str
     * @param formatStr
     * @return
     * @throws ParseException
     */
    public static Date strToDate(String str, String formatStr) throws ParseException {
        return SimpleDateFormatInit.getSimpleDateFormat(formatStr).parse(str);
    }

    private static class SimpleDateFormatInit {
        private static SimpleDateFormat simpleDateFormat;

        private static SimpleDateFormat getSimpleDateFormat(String formatStr) {
            if (simpleDateFormat == null) {
                simpleDateFormat = new SimpleDateFormat();
            }
            simpleDateFormat.applyPattern(formatStr);
            return simpleDateFormat;
        }
    }
}
